package com.vs.meepet.network

import com.vs.meepet.utils.LogUtils
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

/**
 * 作者：柯嘉少
 * 邮箱：2449926649@qq.com
 * 日期: 2023/11/14
 * 修改人: xxx(des)
 * 说明:创建Retrofit公共请求类（kotlin 协程+dsl+retrofit简化网络请求的写法）
 * 版本: 1.0
 */
class RetrofitClient {
    private constructor()

    companion object {
        val instance: RetrofitClient by lazy { RetrofitClient() }
    }

    /**
     * 构建retrofit实例（base url为host）
     * 说明：例子，使用getRetrofitClient().create(ServiceApi::class.java)构建请求实例
     */
    fun getCommonRetrofitClient(baseUrl:String): Retrofit {
        val retrofitClient = Retrofit.Builder()
            .baseUrl(baseUrl)
            .client(
                HttpConfig.getOkHttpClient()
                    .newBuilder()
                    //.retryOnConnectionFailure(true)//设置失败重试一次，如果要多次，需要自定义拦截器
                    .addInterceptor(Interceptor { chain ->
                        //这里就可以添加一些通用请求头了
                        val request: Request = chain.request()
                            .newBuilder()
                            .addHeader("User-Agent", UAManager.getUserAgent())
                            .build()
                        chain.proceed(request)
                    })
                    //添加日志打印
                    /*.addInterceptor(
                        HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)
                    )*/
                    .apply {
                        this.addInterceptor(
                            getLogInterceptor()
                        )
                    }.build()
            )
            .addConverterFactory(GsonConverterFactory.create())
            .build()
        return retrofitClient
    }

}

private fun getLogInterceptor(): HttpLoggingInterceptor {
    val loggingInterceptor = HttpLoggingInterceptor() { message -> //打印retrofit日志
        LogUtils.d(message)
    }
    loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
    return loggingInterceptor
}